<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :inline="true" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-col :span="12">
        <el-form-item label="用户名" prop="userName" :class="{ 'is-required': true }">
          <el-input v-model="dataForm.userName" placeholder="登录帐号"></el-input>
        </el-form-item>     
        <!--
        <el-form-item label="机构ID" prop="userName">
          <el-input v-model="dataForm.tenantId" placeholder="机构ID"></el-input>
        </el-form-item>-->
      </el-col>
      <el-col :span="12">

        <el-form-item label="邮箱" prop="email" :class="{ 'is-required': true }">
          <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
        </el-form-item>
      </el-col>
      
      <el-col :span="12">
        <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
          <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
          <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
        </el-form-item>
      </el-col>
      <!--:disabled="this.$cookie.get('level') == 1 || this.$cookie.get('level') == 2 || dataForm.id" -->
      <el-col :span="12" v-if="(this.$cookie.get('level') == 0 ||this.$cookie.get('level') == 1 || this.$cookie.get('level') == 2 || this.$cookie.get('level') == 3)">
        <el-form-item label="省" prop="province" :class="{ 'is-required': this.$cookie.get('level') == 0 && !dataForm.id }">
          <el-select v-model="dataForm.province" clearable :disabled="this.$cookie.get('level') == 1 || this.$cookie.get('level') == 2 || this.$cookie.get('level') == 3 || dataForm.id" placeholder="请选择" @change="loadCity">
            <el-option
              v-for="item in provinceList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!--:disabled="this.$cookie.get('level') == 2 || dataForm.id"-->
      <el-col :span="12" v-if="this.$cookie.get('level') == 1 || this.$cookie.get('level') == 2 || this.$cookie.get('level') == 3">
        <el-form-item label="市" prop="city" :class="{ 'is-required': this.$cookie.get('level') == 1 && !dataForm.id }">
          <el-select v-model="dataForm.city" clearable :disabled="this.$cookie.get('level') == 2 || this.$cookie.get('level') == 3 || dataForm.id"  placeholder="请选择" @change="loadCountry">
            <el-option
              v-for="item in cityList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <!--:disabled="this.$cookie.get('level') == 2 || dataForm.id"-->
      <el-col :span="12" v-if="this.$cookie.get('level') == 2 || this.$cookie.get('level') == 3">
        <el-form-item label="县" prop="country" :class="{ 'is-required': this.$cookie.get('level') == 2 && !dataForm.id }">
          <el-select v-model="dataForm.country" clearable :disabled="this.$cookie.get('level') == 3 || dataForm.id" placeholder="请选择">
            <el-option
              v-for="item in countryList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="单位" prop="employer">
          <el-input v-model="dataForm.employer" placeholder="单位"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="职务" prop="position">
          <el-input v-model="dataForm.position" placeholder="职务"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系手机" prop="mobile">
          <el-input v-model="dataForm.mobile" placeholder="联系手机"></el-input>
        </el-form-item>
      </el-col>

      <!--v-if="this.$cookie.get('userId') == 1"-->
      <el-form-item v-if="this.$cookie.get('userId') == 1" label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox
           v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!--
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('确认密码不能为空'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        roleList: [],
        provinceList:[],
        cityList:[],
        countryList:[],
        level: this.$cookie.get('level'),
        dataForm: {
          id: 0,
          userName: '',
          //tenantId: '1',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          roleIdList: [],
          //status: 1
          province: '',
          city: '',
          country: '',
          employer: '',
          position: ''
        },
        dataRule: {
          userName: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ],
          tenantId: [
            { required: true, message: '机构ID不能为空', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0;
        
        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/frt/district/select'),
            method: 'get',
            params: this.$http.adornParams({
              'level': 1
            })
          }).then(({data}) => {
            this.provinceList = data.list;
          })
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userName = data.user.username;
                //this.dataForm.tenantId = data.user.tenantId
                this.dataForm.salt = data.user.salt;
                this.dataForm.email = data.user.email;
                this.dataForm.mobile = data.user.mobile;
                this.dataForm.roleIdList = data.user.roleIdList;
                //this.dataForm.status = data.user.status
                this.dataForm.province = data.user.province;
                
                this.dataForm.city = data.user.city;
                this.dataForm.country = data.user.country;
                if(this.dataForm.province){
                  this.loadCity(this.dataForm.province);
                }
                if(this.dataForm.city){
                  this.loadCountry(this.dataForm.city);
                }

                this.dataForm.employer = data.user.employer;
                this.dataForm.position = data.user.position;
              }
            })
          }else{
            if(this.$cookie.get('province') != 'null'){
              this.dataForm.province = this.$cookie.get('province');

              this.loadCity(this.dataForm.province);
            }
            if(this.$cookie.get('city') != 'null'){
              this.dataForm.city = this.$cookie.get('city');
              this.loadCountry(this.dataForm.city);
            }
            if(this.$cookie.get('country') != 'null'){
              this.dataForm.country = this.$cookie.get('country');
            }
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.id || undefined,
                'username': this.dataForm.userName,
                //'tenantId': this.dataForm.tenantId,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                //'status': this.dataForm.status,
                'roleIdList': this.dataForm.roleIdList,
                'province': this.dataForm.province,
                'city': this.dataForm.city,
                'country': this.dataForm.country,
                'employer': this.dataForm.employer,
                'position': this.dataForm.position,
                'level': this.$cookie.get('level')
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      //加载市级行政区
      loadCity(curVal){
        this.cityList = [];
        this.$http({
            url: this.$http.adornUrl('/frt/district/select'),
            method: 'get',
            params: this.$http.adornParams({
              'level': 2,
              'parentCode': curVal
            })
          }).then(({data}) => {
            this.cityList = data.list;
          })
      },
      //加载县级行政区
      loadCountry(curVal){
        this.countryList = [];
        this.$http({
            url: this.$http.adornUrl('/frt/district/select'),
            method: 'get',
            params: this.$http.adornParams({
              'level': 3,
              'parentCode': curVal
            })
          }).then(({data}) => {
            this.countryList = data.list;
          })
      }
    }
  }
</script>
